// 全局变量
let sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
let isConnected = false;
let websocket = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，初始化聊天应用...');
    
    // 添加全局错误处理
    window.addEventListener('error', function(e) {
        console.error('全局错误:', e.error);
        alert('发生错误: ' + e.error.message);
    });
    
    // 检查必要的API支持
    if (!window.fetch) {
        alert('您的浏览器不支持fetch API，请使用现代浏览器');
        return;
    }
    
    try {
        initChatApp();
        console.log('聊天应用初始化成功');
    } catch (error) {
        console.error('初始化失败:', error);
        alert('初始化失败: ' + error.message);
    }
});

// 初始化聊天应用
function initChatApp() {
    console.log('开始初始化聊天应用...');
    
    // 获取DOM元素
    const sendButton = document.getElementById('sendButton');
    const messageInput = document.getElementById('messageInput');
    const clearButton = document.getElementById('clearButton');
    const connectionStatus = document.getElementById('connectionStatus');
    const currentTimeElement = document.getElementById('currentTime');
    const exampleButtons = document.querySelectorAll('.example-btn');
    
    // 检查关键元素
    if (!sendButton) {
        throw new Error('发送按钮未找到');
    }
    if (!messageInput) {
        throw new Error('输入框未找到');
    }
    
    console.log('DOM元素获取成功');
    
    // 绑定事件
    sendButton.addEventListener('click', function() {
        console.log('发送按钮被点击');
        handleSendMessage();
    });
    
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            console.log('回车键被按下');
            e.preventDefault();
            handleSendMessage();
        }
    });
    
    if (clearButton) {
        clearButton.addEventListener('click', function() {
            console.log('清除按钮被点击');
            handleClearHistory();
        });
    }
    
    // 绑定示例按钮
    exampleButtons.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const message = btn.getAttribute('data-message');
            console.log('示例按钮被点击:', message);
            messageInput.value = message;
            handleSendMessage();
        });
    });
    
    // 更新连接状态
    updateConnectionStatus('已连接 (HTTP)');
    
    // 更新时间
    updateCurrentTime();
    setInterval(updateCurrentTime, 60000);
    
    // 尝试WebSocket连接
    connectWebSocket();
    
    console.log('事件绑定完成');
}

// 处理发送消息
async function handleSendMessage() {
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    
    const message = messageInput.value.trim();
    if (!message) {
        console.log('消息为空，跳过发送');
        return;
    }
    
    console.log('准备发送消息:', message);
    
    // 添加用户消息到界面
    addMessageToChat(message, 'user');
    messageInput.value = '';
    
    // 禁用发送按钮
    sendButton.disabled = true;
    sendButton.textContent = '发送中...';
    
    // 显示输入指示器
    showTypingIndicator();
    
    try {
        // 发送消息到服务器
        const response = await fetch('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                sessionId: sessionId,
                message: message
            })
        });
        
        console.log('收到服务器响应，状态:', response.status);
        
        if (!response.ok) {
            throw new Error(`服务器错误: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('响应数据:', data);
        
        // 移除输入指示器
        removeTypingIndicator();
        
        // 添加AI回复到界面
        addMessageToChat(data.content, 'assistant', data.timestamp);
        
    } catch (error) {
        console.error('发送消息失败:', error);
        removeTypingIndicator();
        addMessageToChat('抱歉，发送消息时出现了错误: ' + error.message, 'assistant');
    } finally {
        // 重新启用发送按钮
        sendButton.disabled = false;
        sendButton.textContent = '发送';
    }
}

// 添加消息到聊天界面
function addMessageToChat(content, role, timestamp) {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('聊天消息容器未找到');
        return;
    }
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}`;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    contentDiv.innerHTML = formatMessageContent(content);
    
    const timeDiv = document.createElement('div');
    timeDiv.className = 'message-time';
    timeDiv.textContent = timestamp || getCurrentTime();
    
    messageDiv.appendChild(contentDiv);
    messageDiv.appendChild(timeDiv);
    
    chatMessages.appendChild(messageDiv);
    scrollToBottom();
    
    console.log('添加消息到界面:', role, content.substring(0, 50) + '...');
}

// 格式化消息内容
function formatMessageContent(content) {
    return content
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>');
}

// 显示输入指示器
function showTypingIndicator() {
    removeTypingIndicator();
    
    const chatMessages = document.getElementById('chatMessages');
    const typingDiv = document.createElement('div');
    typingDiv.className = 'message assistant';
    typingDiv.id = 'typing-indicator';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'typing-indicator';
    contentDiv.innerHTML = `
        <div class="typing-dots">
            <span></span>
            <span></span>
            <span></span>
        </div>
    `;
    
    typingDiv.appendChild(contentDiv);
    chatMessages.appendChild(typingDiv);
    scrollToBottom();
    
    console.log('显示输入指示器');
}

// 移除输入指示器
function removeTypingIndicator() {
    const typingIndicator = document.getElementById('typing-indicator');
    if (typingIndicator) {
        typingIndicator.remove();
        console.log('移除输入指示器');
    }
}

// 滚动到底部
function scrollToBottom() {
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
}

// 获取当前时间
function getCurrentTime() {
    return new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 更新当前时间显示
function updateCurrentTime() {
    const currentTimeElement = document.getElementById('currentTime');
    if (currentTimeElement) {
        currentTimeElement.textContent = getCurrentTime();
    }
}

// 更新连接状态
function updateConnectionStatus(status) {
    const connectionStatus = document.getElementById('connectionStatus');
    if (connectionStatus) {
        connectionStatus.textContent = status;
        connectionStatus.className = 'connection-status';
    }
}

// 清除聊天历史
async function handleClearHistory() {
    if (!confirm('确定要清除所有聊天记录吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/chat/${sessionId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            const chatMessages = document.getElementById('chatMessages');
            const messages = chatMessages.querySelectorAll('.message');
            messages.forEach((msg, index) => {
                if (index > 0) { // 保留第一条欢迎消息
                    msg.remove();
                }
            });
            console.log('聊天历史已清除');
        } else {
            alert('清除历史记录失败');
        }
    } catch (error) {
        console.error('清除历史记录失败:', error);
        alert('清除历史记录失败: ' + error.message);
    }
}

// WebSocket连接（可选功能）
function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/api/ws/${sessionId}`;
    
    try {
        websocket = new WebSocket(wsUrl);
        
        websocket.onopen = function() {
            console.log('WebSocket连接已建立');
            isConnected = true;
            updateConnectionStatus('已连接 (WebSocket)');
        };
        
        websocket.onmessage = function(event) {
            try {
                const data = JSON.parse(event.data);
                handleWebSocketMessage(data);
            } catch (error) {
                console.error('解析WebSocket消息失败:', error);
            }
        };
        
        websocket.onclose = function() {
            console.log('WebSocket连接已关闭');
            isConnected = false;
            updateConnectionStatus('已连接 (HTTP)');
            
            // 5秒后尝试重连
            setTimeout(connectWebSocket, 5000);
        };
        
        websocket.onerror = function(error) {
            console.error('WebSocket错误:', error);
            isConnected = false;
            updateConnectionStatus('已连接 (HTTP)');
        };
    } catch (error) {
        console.error('WebSocket连接失败:', error);
        isConnected = false;
        updateConnectionStatus('已连接 (HTTP)');
    }
}

// 处理WebSocket消息
function handleWebSocketMessage(data) {
    console.log('收到WebSocket消息:', data);
    
    if (data.type === 'stream') {
        appendToLastMessage(data.content);
    } else if (data.type === 'end') {
        removeTypingIndicator();
    } else if (data.type === 'error') {
        removeTypingIndicator();
        addMessageToChat('抱歉，处理您的请求时出现了错误。', 'assistant');
    }
}

// 追加内容到最后一条消息
function appendToLastMessage(content) {
    const chatMessages = document.getElementById('chatMessages');
    const messages = chatMessages.querySelectorAll('.message.assistant');
    if (messages.length > 0) {
        const lastMessage = messages[messages.length - 1];
        const contentDiv = lastMessage.querySelector('.message-content');
        if (contentDiv) {
            contentDiv.innerHTML += formatMessageContent(content);
            scrollToBottom();
        }
    }
}

console.log('app.js 加载完成，等待页面加载...');
